package com.zhy.springcloud.lb;


import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author zhy
 * @Description
 * @ClassName MyLb
 * @Date 2020/12/2 16:51
 **/
@Component
public class MyLb implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement(){
        int current;
        int next;
        do {
            //获取当前访问次数
            current=this.atomicInteger.get();
            //2147483647 是Java中integer最大值
            next=current >= 2147483647 ? 0 : current+1;
            //cas current：当前内存里面的值，next：要修改的值
            // atomicInteger.compareAndSet：内存中AtomicInteger对象地址对应的真实值(因为有可能别修改)real与current对比
            // 相等表示real未被修改过，是“安全”的，将new赋给real结束然后返回；不相等说明real已经被修改，结束并重新执行1直到修改成功
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("********第几次访问:"+next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        //轮询规则：实际调用服务器位置下表=rest接口第几次请求数%服务器集群总数量
        int index=getAndIncrement() %  serviceInstances.size();

        return serviceInstances.get(index);
    }



}
